/*
Copyright (c) 2010 Neil Wood

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package  envisage.Controls
{
	import envisage.Data.CRange;
	import envisage.Data.IArray;
	
	import flash.display.DisplayObject;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	
	public class List extends Control
	{
		public function List()
		{
			uiArraySubset = new ArraySubset();
			addChild(uiArraySubset);
			uiArraySubset.requireUpdate = RequireLayout;
			//uiArraySubset.Owner = this;
			Owner =this;
			
			super();
			
			NoScale = true;
			
			addEventListener(MouseEvent.CLICK, OnMouseClick);
			
			RequireLayout();
		}
		
		public function set Owner(d:DisplayObject):void { uiArraySubset.Owner = d; }
		
		public function IndexFromItem(item:Object):int
		{
			var len:int = DataArray.GetNumItems();
			for(var i:int = 0 ; i < len ; i++)
				if( DataArray.GetItem(i) == item ) return i;
				
			return -1;
		}
		
		public function IndexFromPoint(p:Point):int
		{
			if( p.x < borderLeft ) return -1;
			if( p.y < borderTop  ) return -1;
			
			var i:Number;
			
			if( orient == Orientation.VERT )
			{
				if( scrollbar == null && p.x > width - borderRight ) return -1;
				if( scrollbar != null && p.x > width - (borderRight + scrollbar.width) ) return -1;
				
				i = p.y;
				i -= borderTop;
				
			}
			
			else
			{
				if( scrollbar == null && p.y > height - borderBottom ) return -1;
				if( scrollbar != null && p.y > height - (borderBottom + scrollbar.height) ) return -1;
				
				i = p.x;
				i -= borderLeft;	
			}
			
			i -= outerPadding;
			i += (offset % (itemSize+innerPadding));
			i /= (itemSize+innerPadding);
			
			var index:int = i;
			index += uiArraySubset.GetVisibleItemTopIndex();
			
			return index;
		}
		
		protected function OnMouseClick(e:MouseEvent):void
		{
			if( DataArray == null ) return;
			
			var index:int = IndexFromPoint(globalToLocal(new Point(e.stageX, e.stageY)));
			
			if( index < 0 || index >= DataArray.GetNumItems() ) return;
			
			ToggleItemSelection(DataArray.GetItem(index));
		}
		
		protected var uiArraySubset:ArraySubset;
		
		
		private var itemSize:Number = 20;
		public function get ItemSize():Number { return itemSize; }
		public function set ItemSize(value:Number):void { if( itemSize != value ) { itemSize = value; RequireLayout(); } }
		
		private var orient:String = Orientation.VERT;
		public function get Orient():String { return orient; }
		public function set Orient(value:String):void { if( this.orient != value ) { orient = value; RequireLayout(); } }
		
		protected var borderLeft:Number   = 0; public function get BorderLeft():Number   { return borderLeft;   }
		protected var borderRight:Number  = 0; public function get BorderRight():Number  { return borderRight;  }
		protected var borderTop:Number    = 0; public function get BorderTop():Number	 { return borderTop;    }
		protected var borderBottom:Number = 0; public function get BorderBottom():Number { return borderBottom; }
		public function SetBorder(left:Number, right:Number, top:Number, bottom:Number):void
		{
			this.borderLeft   = left;
			this.borderRight  = right;
			this.borderTop 	  = top;
			this.borderBottom = bottom;
			RequireLayout();
		}
	
		private var offset:Number = 0;
		public function get Offset():Number { return offset; }
		public function set Offset(value:Number):void { this.offset = value; RequireLayout(); } 
		
		public function get DataArray():IArray { return uiArraySubset.DataArray; } 
		public function set DataArray(value:IArray):void { uiArraySubset.DataArray = value; RequireLayout(); }
		
		public function get PrimarySize():Number { return orient == Orientation.HORZ? ClientWidth : ClientHeight; }
		
		protected function LayoutScrollbar(dataLen:int, total:Number):void
		{
			var vert:Boolean = orient == Orientation.VERT;
			var sbvert:Boolean = scrollbar.Orient == Orientation.VERT;
			
			var visible:Number = vert? ClientHeight : ClientWidth;
			var scroll:Number = total-visible;
				
			if(scroll <= 0 )
			{ 
				scrollbar.visible = false;
				scrollbar.DataRange.SetB(0);
			}
				
			else
			{
				scrollbar.visible = true;
				scrollbar.DataRange.SetB(scroll);
					
				if( sbvert )
				{
					scrollbar.x = width - (borderRight + scrollbar.width);
					scrollbar.y = borderTop;
					scrollbar.height = ClientHeight;
					uiArraySubset.width -= scrollbar.width;
				}
					
				else
				{
					scrollbar.x = borderLeft;
					scrollbar.y = height - (borderBottom + scrollbar.height);
					scrollbar.width = ClientWidth;
					uiArraySubset.height -= scrollbar.height;
				}
					
				scrollbar.VisibleRatio = visible / total;
			}
		}
		
		protected function LayoutVisibleItems(dataLen:int, vert:Boolean):void
		{	
			var newTop:int = (offset-outerPadding) / (itemSize + innerPadding);
			if( newTop < 0 ) newTop = 0;
			else if( newTop > dataLen ) newTop = dataLen;
			
			var amt:Number = vert ? ClientHeight : ClientWidth;
			var newBot:int = (newTop + Math.ceil(amt / (itemSize+innerPadding)))+1;
			if( newBot > dataLen ) newBot = dataLen;
			if( newBot < newTop ) newBot = newTop;
			
			uiArraySubset.SetVisibleItemsTopIndex(newTop);
			uiArraySubset.SetVisibleItemsLength(newBot-newTop);
			
			if( vert ) LayoutChildren(borderLeft, (-(offset % (itemSize+innerPadding))) + borderTop + outerPadding, 0, (itemSize + innerPadding), 0, Number.POSITIVE_INFINITY);
			else 	   LayoutChildren((-(offset % (itemSize+innerPadding))) + borderLeft + outerPadding, borderTop, (itemSize+innerPadding), 0, Number.POSITIVE_INFINITY, 0);
			
		}
		
		protected function LayoutChildren(left:Number, top:Number, hAdd:Number, vAdd:Number, hEnd:Number, vEnd:Number):void
		{
			var newTop:int = uiArraySubset.GetVisibleItemTopIndex();
			var newBot:int = uiArraySubset.GetVisibleItemsLength() + newTop;
			
			var x:Number = left;
			var y:Number = top;
			for(var i:int = newTop; i < newBot ; i++)
			{
				var c:DisplayObject = uiArraySubset.GetControl(i);
				
				c.x = x;
				c.y = y;
				
				if( orient == Orientation.VERT ) 
				{
					x += hAdd;
					if( x >= hEnd ) 
					{
						x = left;
						y += vAdd;
					}
				}
				
				else
				{
					y += vAdd;
					if( y >= vEnd )
					{
						y = top;
						x += hAdd;
					}
				}		
					
				LayoutSizeChild(c, i);
			}
		}
		
		protected function LayoutSizeChild(c:DisplayObject, index:int):void
		{
			var v:Number = 0;
			if( scrollbar != null ) v = scrollbar.Orient == Orientation.HORZ? scrollbar.height : scrollbar.width;
			
			if( resizeItems )
			{
				if( orient == Orientation.HORZ ) { c.width = itemSize; 	c.height = ClientHeight -v; }
				else						  { c.width = ClientWidth-v;  c.height = itemSize; 	 }
			}
		}
		
		public function get ClientWidth():Number { return width - (borderLeft + borderRight); }
		public function get ClientHeight():Number{ return height- (borderTop  + borderBottom); }
		
		protected override function Layout():void
		{	
			var iData:IArray = DataArray;
			if( iData == null ) return;
			
			var dataLen:int = iData.GetNumItems();
			
			uiArraySubset.x = borderLeft;
			uiArraySubset.y = borderTop;
			uiArraySubset.width = ClientWidth;
			uiArraySubset.height = ClientHeight;
			
			var vert:Boolean = orient == Orientation.VERT;
			
			if( scrollbar != null )
			{
				var total:Number = (dataLen * itemSize) + (outerPadding * 2) + (Math.max(dataLen-1, 0) * innerPadding);
				total += itemSize / 2; //extra space for dropping after final member when scrolling activated
				LayoutScrollbar(dataLen, total);
			}
			
			LayoutVisibleItems(dataLen, vert);
		}
		
		private var innerPadding:Number = 0;
		public function get InnerPadding():Number { return innerPadding; }
		public function set InnerPadding(value:Number):void { if( this.innerPadding != value ) { innerPadding = value; RequireLayout(); } }
		
		private var outerPadding:Number = 0;
		public function get OuterPadding():Number { return outerPadding; }
		public function set OuterPadding(value:Number):void { if( this.outerPadding != value ) { outerPadding  = value; RequireLayout(); }} 
		
		private var resizeItems:Boolean = true;
		public function get ResizeItems():Boolean { return resizeItems; }
		public function set ResizeItems(value:Boolean):void { this.resizeItems = value; RequireLayout(); }
		
		private var scrollbar:Scrollbar;
		public function get _Scrollbar():Scrollbar { return scrollbar; }
		public function set _Scrollbar(value:Scrollbar):void
		{
			this.scrollbar = value; RequireLayout();
			scrollbar.DataRange = new CRange(0, 0, 0);
			scrollbar.addEventListener(EnvisageEvent.UPDATED, OnSliderUpdate);
		}
		
		private function OnSliderUpdate(e:EnvisageEvent):void
		{
			Offset = e.data as Number;
		}
		
		
		public function set itemClassName(value:String):void { uiArraySubset.itemClassName = value; }		
		public function set modify(value:Function):void { uiArraySubset.modify = value; 	   }
		
		public function get itemClassName():String { return uiArraySubset.itemClassName; }
		public function get modify():Function { return uiArraySubset.modify; }
		
		private var multipleSelection:Boolean = false;
		public function MultipleSelection(value:Boolean):void { multipleSelection = value; }
		
		public function SetItemSelected(item:Object, selected:Boolean):void
		{
			if( selected == true && multipleSelection == false && uiArraySubset.GetSelected().length != 0 )
				SetItemSelected(uiArraySubset.GetSelected()[0], false);
			
			if( uiArraySubset.SetItemSelected(item, selected) )
				dispatchEvent(new EnvisageEvent(selected? EnvisageEvent.SELECTED : EnvisageEvent.DESELECTED, item, uiArraySubset.ControlFromObject(item), this));
		}
		
		public function ToggleItemSelection(item:Object):void
		{
			SetItemSelected(item, ! GetItemSelected(item));
		}
		
		public function GetItemSelected(item:Object):Boolean
		{
			return uiArraySubset.GetItemSelected(item);
		}
		
		public function GetSelectedItem():Object
		{
			return uiArraySubset.GetSelected()[0];
		}
		
		public function InvalidateItems():void
		{
			for(var i:int = uiArraySubset.GetVisibleItemTopIndex() ; i < uiArraySubset.GetVisibleItemTopIndex() + uiArraySubset.GetVisibleItemsLength() ; i++)
			{
				uiArraySubset.InvalidateItem(i);
			}
		}
	}
}




